import logs from '@/models/logs';
import { analysisToken } from '@/utils/Auth/auth';
import { logTypeText, logType } from '@/utils/data';
import { replaceText } from '@/utils/tools';
import dayjs from 'dayjs';
import { ObjectId } from 'mongodb';

// type：操作类型 typeText：文案类型 name：操作人 data：占位数据
export const addLogs = async (type, typeText, name, data, userId) => {
  try {
    const text = replaceText(data, logTypeText[typeText]);
    await logs.insert({
      type: logType[type],
      typeText: text,
      name,
      time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      userId,
    });
  } catch (err) {
    console.log(err);
  }
};

export const getList = async (params) => {
  const { page, pageSize, token, ...others } = params;
  const query = { ...others };
  if (query.time) {
    query.time = new RegExp(params.time);
  }
  if (query.name) {
    query.name = new RegExp(params.name);
  }
  const info: any = await analysisToken(token);
  const { personId, role } = info;
  // 管理员用户64feec8ae6de3ece9c58b57f返回所有日志。其他用户返回自己的日志
  if (role !== '64feec8ae6de3ece9c58b57f') {
    query.userId = { $in: [new ObjectId(personId), personId] };
  }
  const res = await logs.getListPagination(query, { time: -1 }, page, pageSize);
  return res;
};
